package cn.sc.summer.construction.sysimpl;

import cn.sc.summer.constant.rabbit.RabbitConstant;
import cn.sc.summer.email.util.EmailUtil;
import cn.sc.summer.rabbitmq.enums.RabbitErrorMessageTypeEnum;
import cn.sc.summer.rabbitmq.po.RabbitMessage;
import cn.sc.summer.rabbitmq.service.RabbitConsumerService;
import cn.sc.summer.rabbitmq.util.RabbitUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 类名：邮件发送实现类
 *
 * @author a-xin
 * @date 2024/3/27 16:14
 */
@Slf4j
@Service
public class EmailSendImpl extends RabbitConsumerService {

    /**
     * 接口: 消费接口信息
     *
     * @param jsonStr 消息体
     * @param message rabbit消息体
     * @param channel rabbit队列
     * @author a-xin
     * @date 2023/9/23 15:48
     */
    @Override
    @RabbitListener(queues = RabbitConstant.EMAIL_SEND_QUEUE)
    public void consumer(String jsonStr, Message message, Channel channel) {
        try {
            RabbitMessage<Map<String, Object>> mapRabbitMessage = RabbitUtil.checkMessage(jsonStr, new TypeReference<Map<String, Object>>() {});
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            if (mapRabbitMessage.getFlag()) {
                Map<String, Object> mapMessage = mapRabbitMessage.getMessage();
                EmailUtil.sendEmail("微服务实例变化通知", mapMessage);
            } else {
                log.error("==> 接收到重复消费消息：Queue: {}, Exchange : {}, RoutingKey : {}, Message : {}",
                        RabbitConstant.EMAIL_SEND_QUEUE,
                        RabbitConstant.EMAIL_SEND_EXCHANGE,
                        RabbitConstant.EMAIL_SEND_ROUTING_KEY,
                        jsonStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            rabbitErrorService.exchangeMessage(e.getMessage(), jsonStr, RabbitErrorMessageTypeEnum.SMS_WRITE);
        }

    }

}
